
import axios from 'axios'
import QS from 'querystring'
import {defaultVue} from "../main";

export function ajax(url, data={ },type='GET') {

    return new Promise(function (resolve, reject) {
        // 执行异步ajax请求
        let promise
        if (type === 'GET') {
            // 准备url query参数数据
            let dataStr = '' //数据拼接字符串
            Object.keys(data).forEach(key => {
                dataStr += key + '=' + data[key] + '&'
            })
            if (dataStr !== '') {
                dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
                url = url + '?' + dataStr
            }
            // 发送get请求
            promise = axios.get(url)
        } else {
            // 发送post请求
            data = QS.stringify(data)
            promise = axios.post(url, data,{headers:{'Content-Type':'application/x-www-form-urlencoded'}})
        }
        promise.then(function (response) {
            // 成功了调用resolve()
            resolve(response.data) //返回 response的data
        }).catch(function (error) {
            //失败了调用reject()
            console.log(error);
            reject(error)
        })

    })
}


export  function ajaxFile(url, data) {
    return new Promise(function (resolve, reject) {
        // 执行异步ajax请求
        let promise
        // 发送post请求
        //data = QS.stringify(data)
        //console.log("ajaxFile")
        promise = axios.post(url, data)
        promise.then(function (response) {
            // 成功了调用resolve()
            //console.log(response.data);
            resolve(response.data) //返回 response的data
        }).catch(function (error) {
            //失败了调用reject()
            console.log(error);
            reject(error)
        })
    })
}

export function ajaxWithResult(url,data,operationName = '操作') {
    /*console.log(defaultVue);
    defaultVue.$message({
      message: '恭喜你，这是一条成功消息',
      type: 'success'
    });*/
    return new Promise(function (resolve,reject) {
        let ajaxPromise = ajax(url,data,"POST");
        ajaxPromise.then(function (response) {
            let res = response;
            // console.log(res);
            if(res.operationCode === "success"){
                defaultVue.$message({
                    message:`${operationName}成功`,
                    type: 'success'
                });
            }else if(res.operationCode === "error"){
                let msg = '';
                if( 'message' in res){
                    msg = res.message;
                }
                defaultVue.$message.error(`${operationName}失败,提示信息${msg}`);
            }
            resolve(res.updateData);
        }).catch(function (error) {
            console.error(error);
            defaultVue.$message.error(`出错了！`);
            reject(error);
        })
    })
}

